package com.roads.site.controller;

import com.roads.common.annotation.Log;
import com.roads.common.config.MasterConfig;
import com.roads.common.constant.Constants;
import com.roads.common.constant.HttpStatus;
import com.roads.common.constant.ResultConstants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.FileEntity;
import com.roads.common.core.page.TableDataInfo;
import com.roads.common.enums.BusinessType;
import com.roads.common.exception.file.InvalidExtensionException;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.StringUtils;
import com.roads.common.utils.file.FileUploadUtils;
import com.roads.common.utils.file.FileUtils;
import com.roads.common.utils.file.MimeTypeUtils;
import com.roads.common.utils.poi.ExcelUtils;
import com.roads.common.utils.uuid.IdUtils;
import com.roads.project.domain.ProInstitution;
import com.roads.project.service.IProInstitutionService;
import com.roads.site.constant.LabourConstant;
import com.roads.site.domain.SiteLabourBattalion;
import com.roads.site.domain.SiteLabourPost;
import com.roads.site.domain.SiteLabourStaff;
import com.roads.site.domain.SiteLabourStaffBank;
import com.roads.site.domain.SiteLabourStaffContract;
import com.roads.site.domain.SiteLabourStaffContractAnnex;
import com.roads.site.domain.SiteLabourStaffRecord;
import com.roads.site.domain.SiteLabourTeam;
import com.roads.site.domain.card.CardModel;
import com.roads.site.domain.vo.StaffBasicModel;
import com.roads.site.domain.vo.StaffEnterModel;
import com.roads.site.service.ISiteLabourBattalionService;
import com.roads.site.service.ISiteLabourPostService;
import com.roads.site.service.ISiteLabourStaffBankService;
import com.roads.site.service.ISiteLabourStaffContractAnnexService;
import com.roads.site.service.ISiteLabourStaffContractService;
import com.roads.site.service.ISiteLabourStaffRecordService;
import com.roads.site.service.ISiteLabourStaffService;
import com.roads.site.service.ISiteLabourTeamService;
import com.roads.site.utils.BaiduHttpUtils;
import com.roads.site.utils.CardUtils;
import com.roads.system.domain.DictNation;
import com.roads.system.domain.DictProvince;
import com.roads.system.service.IDictService;
import net.lingala.zip4j.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

/**
 * 农民工花名册Controller
 * 
 * @author nhp
 * @date 2022-10-27
 */
@RestController
@RequestMapping("/labour/staff")
public class SiteLabourStaffController extends BaseController {

    @Autowired
    private ISiteLabourStaffService service;

    @Autowired
    private ISiteLabourBattalionService battalionService;

    @Autowired
    private ISiteLabourTeamService teamService;

    @Autowired
    private ISiteLabourPostService postService;

    @Autowired
    private IProInstitutionService institutionService;

    @Autowired
    private ISiteLabourStaffRecordService recordService;

    @Autowired
    private ISiteLabourStaffContractService contractService;

    @Autowired
    private ISiteLabourStaffContractAnnexService contractAnnexService;

    @Autowired
    private ISiteLabourStaffBankService bankService;

    @Autowired
    private IDictService dictService;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:list')")
    @GetMapping("/list")
    public TableDataInfo list(SiteLabourStaff model) {
        startPage();
        List<SiteLabourStaff> list = service.selectModelList(model);
        return getDataTable(list);
    }

    /**
     * 劳务工花名册查询下拉初始化
     *
     * @param institutionCode 机构编号
     * @return 劳务工花名册相关下拉框数据
     */
    @GetMapping("/initSearchSelect")
    public AjaxResult initSearchSelect(String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        List<SiteLabourBattalion> battalions = battalionService.dropDownList(institutionCode);
        ajaxResult.put("battalions", battalions);
        List<SiteLabourPost> posts = postService.dropDownList(institutionCode);
        ajaxResult.put("posts", posts);
        List<SiteLabourTeam> teams = teamService.dropDownList(institutionCode);
        ajaxResult.put("teams", teams);
        List<DictNation> nations = dictService.getNationList();
        ajaxResult.put("nations", nations);
        List<DictProvince> provinces = dictService.getProvinceList();
        ajaxResult.put("provinces", provinces);
        return ajaxResult;
    }

    /**
     * 劳务工下拉框
     *
     * @param institutionCode 劳务工下拉框
     * @return 劳务工下拉框
     */
    @GetMapping("/dropDownListBySalary")
    public AjaxResult dropDownListBySalary(String institutionCode, Integer masterId) {
        AjaxResult ajaxResult = new AjaxResult();
        List<SiteLabourStaff> staffs = service.dropDownListBySalary(institutionCode, masterId);
        ajaxResult.put("staffs", staffs);
        return ajaxResult;
    }

    /**
     * 导出
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:export')")
    @Log(title = "劳务工花名册", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SiteLabourStaff model) {
        List<SiteLabourStaff> list = service.selectModelList(model);
        ExcelUtils<SiteLabourStaff> util = new ExcelUtils<SiteLabourStaff>(SiteLabourStaff.class);
        return util.exportExcel(list, "劳务工花名册数据");
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(service.getModelById(id));
    }

    /**
     * 查看详细信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:query')")
    @GetMapping(value = "/browse/{id}")
    public AjaxResult browse(@PathVariable("id") Integer id) {
        AjaxResult ajaxResult = new AjaxResult();
        SiteLabourStaff staff = service.getModelById(id);
        ProInstitution institution = institutionService.getModelByInnerCode(staff.getInstitutionCode());
        ajaxResult.put("staff", staff);
        ajaxResult.put("bidName", institution.getInstitutionName());
        // 查询从业记录
        List<SiteLabourStaffRecord> records = recordService.selectModelListByIdNo(staff.getIdNo());
        ajaxResult.put("records", records);
        // 查询合同信息
//        List<SiteLabourStaffContract> contracts = contractService.selectModelListByIdNo(staff.getIdNo());
//        ajaxResult.put("contracts", contracts);
        return ajaxResult;
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工花名册", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SiteLabourStaff model) {
        // 查看劳务工是否已经添加，并且查看是否在其他标段在岗状态
        List<SiteLabourStaff> dbList = service.selectModeListByIdNo(model.getIdNo());
        for (SiteLabourStaff staff : dbList) {
            if (staff.getInstitutionCode().equals(model.getInstitutionCode())) {
                return error("[" + model.getIdNo() + "]已存在，不能重复添加。");
            }
        }
        model.setCreateBy(getUsername());
        model.setCreateTime(DateUtils.getNowDate());
        return toAjax(service.insert(model));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:edit')")
    @Log(title = "劳务工花名册", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SiteLabourStaff model) {
        model.setUpdateBy(getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return toAjax(service.update(model));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:remove')")
    @Log(title = "劳务工花名册", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(service.deleteByIds(ids));
    }

    /**
     * 身份证上传
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工花名册-身份证上传（单个）", businessType = BusinessType.IMPORT)
    @PostMapping("/cardUpload")
    public AjaxResult cardUpload(@RequestParam("cardFrontFile") MultipartFile cardFrontFile,
                                 @RequestParam("cardBackFile") MultipartFile cardBackFile,
                                 @RequestParam("institutionCode") String institutionCode,
                                 @RequestParam("id") Integer id) {
        long startTime = System.currentTimeMillis();
        String token;
        CardModel card;
        try {
            token = BaiduHttpUtils.getAuth();
        } catch (IOException e) {
            e.printStackTrace();
            return error("获取第三方token失败，请联系管理员");
        }
        try {
            card = CardUtils.cardUpload(token, cardFrontFile, cardBackFile);
            if (ResultConstants.RESULT_ERROR.equals(card.getStatus())) {
                return error(card.getContent());
            }
            // 劳务工ID不为0的情况，就是定向上传身份证，也就是先导入的数据，后上传身份证照片，这个时候需要进行匹配
            if (id != 0) {
                SiteLabourStaff staff = service.getModelById(id);
                if (!staff.getIdNo().equals(card.getIdNo())) {
                    return error("上传的身份证照片与身份证号不匹配");
                }
                if (!staff.getName().equals(card.getCardFront().getName())) {
                    return error("上传的身份证照片与姓名不匹配");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("调用身份证接口错误，请联系管理员");
        }
        AjaxResult ajaxResult = service.cardUpload(cardFrontFile, cardBackFile, institutionCode, card.getCardFront(), card.getCardBack());
        long endTime = System.currentTimeMillis();
        System.out.println("身份证上传耗时：" + (endTime - startTime) + " ms");
        return ajaxResult;
    }

    /**
     * 身份证上传(批量)
     * @param file 压缩文件
     * @param institutionCode 标段编号
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工花名册-身份证上传（批量）", businessType = BusinessType.IMPORT)
    @PostMapping("/cardZipUpload")
    public AjaxResult cardZipUpload(@RequestParam("file") MultipartFile file, @RequestParam("institutionCode") String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        // 获取临时上传路径
        String uuid = IdUtils.fastSimpleUuid();
        String tempPath = MasterConfig.getTempPath() + "/" + uuid;
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(0, fileName.indexOf("."));
        try {
            String zipFileName = FileUploadUtils.tempFileUpload(tempPath, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, uuid);
            File tempFile = new File(tempPath + "/" + zipFileName);
            // 解压
            ZipFile zipFile = new ZipFile(tempFile);
            zipFile.setCharset(Charset.forName(Constants.GBK));
            zipFile.extractAll(tempPath);
            String zipPath = tempPath + "/" + fileName;
            ajaxResult = service.cardZipUpload(institutionCode, zipPath, tempPath);
        } catch (IOException | InvalidExtensionException e) {
            e.printStackTrace();
            FileUtils.deleteDirectory(new File(tempPath));
            ajaxResult.put("status", "error");
            ajaxResult.put("msg", "文件上传解压失败");
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 下载劳务工导入模板
     *
     * @return excel模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtils<SiteLabourStaff> utils = new ExcelUtils<>(SiteLabourStaff.class);
        return utils.importTemplateExcel("劳务工数据");
    }

    @Log(title = "劳务工花名册-基本信息", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('labour:staff:import')")
    @PostMapping("/importBasicData")
    public AjaxResult importBasicData(MultipartFile file, String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        ExcelUtils<StaffBasicModel> utils = new ExcelUtils<>(StaffBasicModel.class);
        List<StaffBasicModel> list = null;
        try {
            list = utils.importExcel(file.getInputStream());
            if (StringUtils.isNull(list) || list.size() == 0) {
                ajaxResult.put("status", "error");
                ajaxResult.put("msg", "导入数据不能为空");
                return ajaxResult;
            }
            ajaxResult = service.importBasicData(list, institutionCode);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("status", "error");
            ajaxResult.put("msg", "excel数据解析失败");
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 劳务工进场前的验证
     *
     * @param id 劳务工id
     * @return 结果
     */
    @GetMapping(value = "/beforeEnterValidate/{id}")
    public AjaxResult beforeEnterValidate(@PathVariable("id") Integer id) {
        AjaxResult ajaxResult = new AjaxResult();
        SiteLabourStaff staff = service.getModelById(id);
        List<SiteLabourStaff> dbList = service.selectModeListByIdNo(staff.getIdNo());
        boolean result = true;
        for (SiteLabourStaff db : dbList) {
            if (!db.getInstitutionCode().equals(staff.getInstitutionCode()) && LabourConstant.STAFF_STATUS_MOBILIZED.equals(db.getStatus())) {
                ajaxResult.put("code", HttpStatus.ERROR);
                ajaxResult.put("msg", "该劳务工在其他项目标段为在岗状态，不能进场操作。");
                result = false;
                break;
            }
        }
        if (result) {
            List<SiteLabourBattalion> battalions = battalionService.dropDownList(staff.getInstitutionCode());
            List<SiteLabourTeam> teams = teamService.dropDownList(staff.getInstitutionCode());
            List<SiteLabourPost> posts = postService.dropDownList(staff.getInstitutionCode());
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("name", staff.getName());
            ajaxResult.put("idNo", staff.getIdNo());
            ajaxResult.put("battalions", battalions);
            ajaxResult.put("teams", teams);
            ajaxResult.put("posts", posts);
        }
        return ajaxResult;
    }

    /**
     * 劳务工进场前的验证--app使用
     *
     * @param id 劳务工id
     * @return 结果
     */
    @GetMapping(value = "/app/enterValid/{id}")
    public AjaxResult enterValid(@PathVariable("id") Integer id) {
        AjaxResult ajaxResult = new AjaxResult();
        SiteLabourStaff staff = service.getModelById(id);
        List<SiteLabourStaff> dbList = service.selectModeListByIdNo(staff.getIdNo());
        boolean result = true;
        for (SiteLabourStaff db : dbList) {
            if (!db.getInstitutionCode().equals(staff.getInstitutionCode()) && LabourConstant.STAFF_STATUS_MOBILIZED.equals(db.getStatus())) {
                ajaxResult.put("code", HttpStatus.ERROR);
                ajaxResult.put("msg", "该劳务工在其他项目标段为在岗状态，不能进场操作。");
                result = false;
                break;
            }
        }
        if (result) {
            ajaxResult.put("code", HttpStatus.SUCCESS);
        }
        return ajaxResult;
    }


    /**
     * 劳务工进场
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:enter')")
    @Log(title = "劳务工进场", businessType = BusinessType.INSERT)
    @PostMapping("/enter")
    public AjaxResult enter(@RequestBody SiteLabourStaffRecord model) {
        return toAjax(service.enter(model));
    }

    /**
     * 劳务工退场
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:exit')")
    @Log(title = "劳务工退场", businessType = BusinessType.UPDATE)
    @PostMapping("/exit")
    public AjaxResult exit(@RequestBody SiteLabourStaffRecord model) {
        SiteLabourStaff staff = service.getModelById(model.getStaffId());
        long lEnterDate = staff.getEnterDate().getTime();
        long lExitDate = model.getExitDate().getTime();
        if (lExitDate < lEnterDate) {
            return AjaxResult.error("退场失败，退场日期不能小于进场日期。");
        }
        return toAjax(service.exit(staff, model));
    }

    /**
     * 劳务工退场
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:exit')")
    @Log(title = "劳务工批量退场", businessType = BusinessType.UPDATE)
    @PostMapping("/batchExit")
    public AjaxResult batchExit(Integer[] ids, Date exitDate) {
        // 查询出ids集合
        List<SiteLabourStaff> list = service.selectModelListByIds(ids);
        // 检查退场日期 是否小于进场日期
        boolean flag = false;
        StringBuilder sb = new StringBuilder();
        sb.append("您所选的");
        long lExitDate = exitDate.getTime();
        for (SiteLabourStaff staff : list) {
            long lEnterDate = staff.getEnterDate().getTime();
            if (lExitDate < lEnterDate) {
                sb.append(staff.getName()).append(",");
                flag = true;
            }
        }
        if (flag) {
            sb.substring(0, sb.length());
            String error = sb.substring(0, sb.length() - 1) + "的退场日期小于进场日期.";
            return error(error);
        }
        return toAjax(service.batchExit(ids, exitDate));
    }

    @Log(title = "劳务工-批量进场", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('labour:staff:import')")
    @PostMapping("/importEnterData")
    public AjaxResult importEnterData(MultipartFile file, String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        ExcelUtils<StaffEnterModel> utils = new ExcelUtils<>(StaffEnterModel.class);
        List<StaffEnterModel> list = null;
        try {
            list = utils.importExcel(file.getInputStream());
            if (!StringUtils.isNotNull(list) || list.size() == 0) {
                ajaxResult.put("status", "error");
                ajaxResult.put("msg", "导入数据不能为空");
                return ajaxResult;
            }
            ajaxResult = service.importEnterData(list, institutionCode);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("status", "error");
            ajaxResult.put("msg", "excel数据解析失败");
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 查询合同信息列表
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:list')")
    @GetMapping("/getStaffContractList")
    public TableDataInfo getStaffContractList(SiteLabourStaffContract model) {
        List<SiteLabourStaffContract> list = contractService.selectModelListByIdNo(model.getIdNo());
        return getDataTable(list);
    }

    /**
     * 查询银行账户列表
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:list')")
    @GetMapping("/getStaffBankList")
    public TableDataInfo getStaffBankList(SiteLabourStaffBank model) {
        List<SiteLabourStaffBank> list = bankService.selectModelListByIdNo(model.getIdNo());
        return getDataTable(list);
    }

    /**
     * 获取劳务工-合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:query')")
    @GetMapping(value = "/contract/{id}")
    public AjaxResult getStaffContract(@PathVariable("id") Integer id) {
        return AjaxResult.success(contractService.getModelById(id));
    }

    /**
     * 获取劳务工-银行账户信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:query')")
    @GetMapping(value = "/bank/{id}")
    public AjaxResult getStaffBank(@PathVariable("id") Integer id) {
        return AjaxResult.success(bankService.getModelById(id));
    }

    /**
     * 新增劳务工-合同信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工-合同信息", businessType = BusinessType.INSERT)
    @PostMapping("/addStaffContract")
    public AjaxResult addStaffContract(@RequestBody SiteLabourStaffContract model) {
        model.setCreateBy(getUsername());
        return toAjax(contractService.insert(model));
    }

    /**
     * 新增劳务工-银行账户
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工-银行账户", businessType = BusinessType.INSERT)
    @PostMapping("/addStaffBank")
    public AjaxResult addStaffBank(@RequestBody SiteLabourStaffBank model) {
        model.setCreateBy(getUsername());
        return toAjax(bankService.insert(model));
    }

    /**
     * 修改劳务工-合同信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:edit')")
    @Log(title = "劳务工-合同信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStaffContract")
    public AjaxResult updateStaffContract(@RequestBody SiteLabourStaffContract model) {
        model.setUpdateBy(getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return toAjax(contractService.update(model));
    }

    /**
     * 修改劳务工-银行账户
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:edit')")
    @Log(title = "劳务工-银行账户", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStaffBank")
    public AjaxResult updateStaffBank(@RequestBody SiteLabourStaffBank model) {
        model.setUpdateBy(getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return toAjax(bankService.update(model));
    }

    /**
     * 删除劳务工-合同信息
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:remove')")
    @Log(title = "劳务工-合同信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/delStaffContract/{ids}")
    public AjaxResult delStaffContract(@PathVariable Integer[] ids) {
        return toAjax(contractService.deleteByIds(ids));
    }

    /**
     * 删除-劳务工-银行账户
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:remove')")
    @Log(title = "劳务工-银行账户", businessType = BusinessType.DELETE)
    @DeleteMapping("/delStaffBank/{ids}")
    public AjaxResult delStaffBank(@PathVariable Integer[] ids) {
        return toAjax(bankService.deleteByIds(ids));
    }

    /**
     * 劳务工-合同附件列表
     *
     * @param uuid uuid
     * @return 附件集合
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:list')")
    @GetMapping("/getStaffContractFileList")
    public AjaxResult fileList(String uuid) {
        SiteLabourStaffContractAnnex search  = new SiteLabourStaffContractAnnex();
        search.setUuid(uuid);
        List<SiteLabourStaffContractAnnex> list = contractAnnexService.selectModelList(search);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("list", list);
        ajaxResult.put("fileCount", list.size());
        return ajaxResult;
    }

    /**
     * 劳务工-合同附件上传
     *
     * @param file 文件
     * @param uuid uuid
     * @return 结果
     * @throws Exception 异常
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @Log(title = "劳务工-合同附件", businessType = BusinessType.UPLOAD)
    @PostMapping("/contract/file/upload")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult upload(MultipartFile file, String uuid) {
        try{
            SiteLabourStaffContract contract = contractService.getModelByUuid(uuid);
            String uploadPath = MasterConfig.getLabourStaffPath() + "/" + contract.getIdNo() + "/contract/" + uuid;
            String fileName = file.getOriginalFilename();
            FileEntity fileEntity = FileUploadUtils.fileUpload(uploadPath, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            String filePath = fileEntity.getFilePath();
            String rename = filePath.substring(filePath.lastIndexOf("/") + 1);
            SiteLabourStaffContractAnnex annex = new SiteLabourStaffContractAnnex();
            annex.setRefilename(rename);
            annex.setFileName(fileName);
            if (fileEntity.getImage()) {
                annex.setIsImg(Constants.YES);
            } else {
                annex.setIsImg(Constants.NO);
            }
            annex.setFilePath(filePath);
            annex.setUuid(uuid);
            annex.setCreateBy(getUsername());
            annex.setCreateTime(DateUtils.getNowDate());
            contractAnnexService.insert(annex);
            // 增加数量
            contractService.addFileCount(uuid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('labour:staff:remove')")
    @Log(title = "劳务工-合同附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/contract/file/{fileId}")
    public AjaxResult remove(@PathVariable("fileId") Integer fileId) {
        return toAjax(contractAnnexService.delete(fileId));
    }

    /**
     * 劳务工-合同文件下载
     *
     * @param fileId 文件ID
     * @param response 响应
     * @param request 请求
     */
    @PostMapping("/contract/file/download")
    public void download(Integer fileId, HttpServletResponse response, HttpServletRequest request) {
        try {
            SiteLabourStaffContractAnnex annex = contractAnnexService.getModelById(fileId);
            SiteLabourStaffContract contract = contractService.getModelByUuid(annex.getUuid());
            String fileName = annex.getFileName();
            String filePath = MasterConfig.getLabourStaffPath()
                    + "/" + contract.getIdNo() + "/contract/" + annex.getUuid() + "/" + annex.getRefilename();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置银行账户默认
     */
    @PreAuthorize("@ss.hasPermi('labour:staff:add')")
    @GetMapping(value = "/setStaffBankTop/{id}")
    public AjaxResult setStaffBankTop(@PathVariable("id") Integer id) {
        return AjaxResult.success(bankService.setTop(id));
    }

}
